package com.itheima.Demo;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class Demo2 {

    private SqlSession sqlSession;
    private InputStream is;

        @Before
    public void init() throws Exception{
            //加载核心配置文件
            is = Resources.getResourceAsStream("MybatisConfig.xml");
            //获取SqlSession工厂对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            //通过SqlSession工厂对象获取SqlSession对象
            sqlSession = factory.openSession();
            //执行映射配置文件中的sql语句，并返回结果
            //处理结果
        }

        @After
    public void destory()throws Exception{
            sqlSession.commit();//手动提交事务
           sqlSession.close();
           is.close();
        }

        @Test
    public void findAll(){
            List<User> users = sqlSession.selectList("UserMapper.findAll");
            for (User user : users) {
                System.out.println(user);
            }
        }

        @Test
    public void findById(){
            User u = sqlSession.selectOne("UserMapper.findById",20);
            System.out.println(u);
        }

        @Test
    public void findCount(){
            int count = sqlSession.selectOne("UserMapper.findCount");
            System.out.println(count);
        }


        @Test
    public void findByName(){
            List<User> users = sqlSession.selectList("UserMapper.findByName", "张");
            for (User u : users) {
                System.out.println(u);
            }
        }

    @Test
    public void findByName2(){
        List<User> users = sqlSession.selectList("UserMapper.findByName2", "李");
        for (User u : users) {
            System.out.println(u);
        }
    }



    @Test
    public void saveReturnId(){
            User u=new User();
            u.setName("匿名");
            u.setGender("性别");
        System.out.println("保存之前"+u);
        sqlSession.insert("UserMapper.saveReturnId",u);
        System.out.println("保存之后"+u);
    }

    @Test
    public void saveReturnId2(){
            User u=new User();
            u.setName("田七");
            u.setGender("45");
        System.out.println("保存之前"+u);
        sqlSession.insert("UserMapper.saveReturnId2",u);
        System.out.println("保存之后"+u);
    }










}

